﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace wwm.LeetCodeHelper.Infrastructure;

/// <summary>
/// 语法树修改,增加ITest接口,增加方法的默认返回值
/// </summary>
internal class MethodReturnDefaultRewriter : CSharpSyntaxRewriter
{
    /// <summary>
    /// 在外层class上添加ITest接口引用
    /// </summary>
    /// <param name="node"></param>
    /// <returns></returns>
    public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        if (node.Modifiers.FirstOrDefault().ValueText == "public" && (node.BaseList == null || node.BaseList.Types == default || !node.BaseList.Types.Any()))
        {
            node = node.WithBaseList(SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType(SyntaxFactory.IdentifierName("ITest")))));
        }
        return base.VisitClassDeclaration(node);
    }
    /// <summary>
    /// 给所有Method添加默认返回值
    /// </summary>
    /// <param name="node"></param>
    /// <returns></returns>
    public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
        var methodDeclaration = (MethodDeclarationSyntax)node;
        string returnType = methodDeclaration.ReturnType.GetText().ToString().Trim();
        if (returnType == "void" || returnType == null) return base.VisitMethodDeclaration(node);
        StatementSyntax returnDefaultText = methodDeclaration.Body.Statements.LastOrDefault() as StatementSyntax;
        if (returnDefaultText != null)
        {
            return base.VisitMethodDeclaration(node);
        }
        var left = SyntaxFactory.IdentifierName(" default");
        returnDefaultText = SyntaxFactory.ReturnStatement(left);
        var new_body = methodDeclaration.Body.AddStatements(returnDefaultText);
        node = node.ReplaceNode(methodDeclaration.Body, new_body);
        return base.VisitMethodDeclaration(node);
    }
}

